package org.ljy.lotterysystem.service.impl;


import lombok.AllArgsConstructor;
import org.ljy.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import org.ljy.lotterysystem.common.exception.ServiceException;
import org.ljy.lotterysystem.common.utils.*;
import org.ljy.lotterysystem.service.IVerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {

    /**
     *  约定redis存储的key，不同业务的key添加不同的前缀
     *  验证码前缀为：VerificationCode_
     */

    private static final String VERIFICATION_CODE_PREFIX = "verification_code_"; //key的前缀
    private static final Long VERIFICATION_CODE_TIMEOUT = 60L; //过期时间
    private static final String VERIFICATION_CODE_TEMPLATE_CODE = "SMS_474855939"; //模版id

    @Autowired
    private SMSUtil smsUtil; //短信服务工具类

    @Autowired
    protected RedisUtil redisUtil; //redis工具类



    @Override
    public void sendVerificationCode(String phoneNumber) {
        //1.验证手机号
        if( !RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_ERROR);
        }
        //2.生成随机验证码
        String code = CaptchaUtil.generateCaptchaCode(4);
        //3.向指定手机用户发送验证码
        Map<String,String> mapCode = new HashMap<String,String>();
        mapCode.put("code", code);
        smsUtil.sendMessage(VERIFICATION_CODE_TEMPLATE_CODE,phoneNumber, JacksonUtil.writeValueAsString(mapCode));
        //4.存储验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber,code,VERIFICATION_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //1.验证手机号
        if( !RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }
}
